package com.byit.controller;


import com.alibaba.fastjson.JSONObject;
import com.byit.domain.SysMenu;
import com.byit.domain.SysRoleMeun;
import com.byit.enums.PromptInfo;
import com.byit.msg.MessageResult;
import com.byit.service.ISysMenuService;
import com.byit.service.ISysRoleMeunService;
import com.byit.shrio.session.SessionHelper;
import com.byit.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 系统菜单列表 前端控制器
 * </p>
 *
 * @author wangx
 * @since 2018-12-11
 */
@RestController
@RequestMapping("/api/sys/sysMenu")
public class SysMenuController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ISysMenuService menuService;
    @Autowired
    private ISysRoleMeunService roleMeunService;

    @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        CustomDateEditor dateEditor = new CustomDateEditor(format, true);
        binder.registerCustomEditor(Date.class, dateEditor);
    }

    @PutMapping("/saveOrUpdate")
    public Object insertMenu(HttpSession session, SysMenu menu) {
        Long userId = SessionHelper.getUserId(session);

        try {
            if (null == menu) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }

            if (menu.getId() != 0) {
                menu.setUpdateTime(new Date());
            } else {
                menu.setCreateTime(new Date());
            }

            menu.setOperationId(userId);
            menuService.insertOrUpdate(menu);
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error();
        }
    }

    @DeleteMapping("/delMenu/{id}")
    public Object delMenu(@PathVariable("id") Long id) {
//        existsChild
        menuService.deleteById(id);
        return MessageResult.success();
    }

    @GetMapping("/selectById/{id}")
    public Object selectMenuById(@PathVariable("id") Long id) {
        SysMenu sysMenu = menuService.selectById(id);
        return MessageResult.success(sysMenu);
    }

    //获取所有后台菜单
    @GetMapping("/selectMenuAll")
    public Object selectMenuAll(){
        List<JSONObject> list = menuService.selectAll();
        return MessageResult.success(list);
    }

    /**
     * 给角色添加菜单
     * @param roleId
     * @param menuIds
     * @return
     */
    @PostMapping("/roleAddMenu")
    public Object roleAddMenu(@RequestParam("roleId") Long roleId,@RequestParam("menuIds") String menuIds){

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("role_id",roleId);
        roleMeunService.deleteByMap(map);
        if (!StringUtil.isNotEmpty(menuIds)){
            return MessageResult.error("请勾选要添加的权限菜单！");
        }

        List<Long> idList = StringUtil.splitLong(menuIds, ",");

        if (0 == idList.size()) {
            return MessageResult.error("请勾选要添加的权限菜单！");
        }
        for (Long menuId:idList
             ) {
            SysRoleMeun sysRoleMeun = new SysRoleMeun();
            sysRoleMeun.setMenuId(menuId);
            sysRoleMeun.setRoleId(roleId);
            roleMeunService.insert(sysRoleMeun);
        }

        return MessageResult.success();

    }

    //获取角色已配置菜单
    @GetMapping("/getRoleMenus")
    public Object getRoleMenus(@RequestParam("roleId") Long roleId){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("roleId",roleId);
        List<JSONObject> list = roleMeunService.selectByRoleId(map);
        return MessageResult.success(list);
    }

}
